<!-- 文件匹配解析 -->
<template>
  <div class="progress-box">
    <h3 class="h3">{{ $t('smt.DocumentComparisonAnalysis') }}</h3>
    <div class="progress-box-header">
      <span class="title">{{ $t('smt.Compatibility') }}：</span>
      <el-progress
        :percentage="100"
        :stroke-width="20"
        :status="status"
        :duration="duration"
        striped
        striped-flow
      >
        <span>{{ typeName }}</span>
      </el-progress>
    </div>
    <div class="info-datas flex f-14">
      <span
        >{{ $t('smt.BOMFile') }}：{{ props.fileUploadRequest?.fileName }}
        <span class="co" @click="downloadBom">{{ $t('smt.download_bom') }}</span>
      </span>
      <span> {{ $t('smt.UploadTime') }}：{{ statisticalData.createTime }} </span>
      <span> {{ $t('smt.TimeofDispatch') }}： {{ statisticalData.updateTime }}</span>
    </div>
    <div v-show="flieData.parseStatus == 4">
      <div class="info-data flex b-t">
        <span class="suess">{{ $t('smt.AllModels') }} : {{ statisticalData.allType }}</span>
        <span class="suess"
          >{{ $t('smt.Numberofmodelsidentified') }} :{{ statisticalData.modelDetermined }}</span
        >
        <span class="icon-co"
          >{{ $t('smt.Numberofmodelstobedetermined') }} :{{
            statisticalData.confirmExactmatch
          }}</span
        >
      </div>
      <div class="info-data flex">
        <span class="icon-co"
          >{{ $t('smt.Numberofunmatchedmodels') }}:
          {{ Number(statisticalData.similarity['2']) || 0 }}</span
        >
        <span class="price"
          >{{ $t('smt.MaterialPrice') }}: ${{ statisticalData.singleBomAmount }}</span
        >
      </div>
      <div class="info-type">
        <span
          ><span class="icon-co">* </span> {{ $t('smt.TheBOMfile') }}
          <span class="icon-co">{{ statisticalData.allType }}</span> {{ $t('smt.models') }}，{{
            $t('smt.pleaseidentifythe')
          }}
          <span class="icon-co">{{ statisticalData.modelConfirmed }}</span>
          {{ $t('smt.notmatchexactly') }}</span
        >
      </div>
    </div>

    <div class="progress-box-footer">
      <div>
        <el-button @click="againUpload">{{ $t('smt.Reupload') }}</el-button>
        <el-button @click="handleClick" :disabled="disabled">{{
          $t('smt.ConfirmationofBOMorder')
        }}</el-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive, onUnmounted, watchEffect } from 'vue';
import { downloadFile } from '@/utils/common.js';

import {
  fileProcessingProgress,
  getQueryPageList,
  getBomMatchListStatisticsData,
} from '../../server/api/biz';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
let timer = null;
const processingType = {
  1: {
    type: t('smt.awaitingprocessing'),
    status: '',
    duration: 0,
  },
  2: {
    type: t('smt.Inprogress'),
    status: '',
    duration: 20,
  },
  3: { type: t('smt.processingfailure'), status: 'exception', duration: 0 },
  4: { type: t('smt.Processingsuccess'), status: 'success', duration: 0 },
};
const duration = ref(20);
const status = ref('');
const typeName = ref(t('smt.Inprogress'));
const bomFileId = ref('');
const props = defineProps({
  fileUploadRequest: {
    type: Object,
    default: null,
  },
  routeType: {
    type: String,
  },
  patchNum: {
    type: [Number, String],
    default: 0,
  },
});
const emit = defineEmits(['reUpload', 'inquireList', 'getCacheData', 'getBomQuote']);
let bomData = ref([]);
const router = useRouter();
const disabled = ref(true);
const flieData = reactive({
  bomName: '',
  fileSerial: '',
  num: '',
  parseStatus: 0,
});

const againUpload = () => {
  emit('reUpload');
};

/**
 * 轮询解析进度
 */
const parsingProgress = () => {
  if (props.fileUploadRequest) {
    // timer = setInterval(() => {
    fileProcessingProgress(props.fileUploadRequest.fileId).then((res) => {
      if (res.code == 200) {
        const data = processingType[res.data.parseStatus];
        duration.value = data.duration;
        status.value = data.status;
        typeName.value = data.type;
        bomFileId.value = res.data.id;
        if (res.data.parseStatus == 4) {
          flieData.bomName = res.data.fileName;
          flieData.fileSerial = res.data.fileSerial;
          flieData.num = res.data.quantity;
          flieData.parseStatus = res.data.parseStatus;
          statisticalData.createTime = res.data.createTime;
          statisticalData.updateTime = res.data.updateTime;
          emit('getBomQuote', props.fileUploadRequest.id);
          getStatisticalData();
          disabled.value = false;
          emit('inquireList');
          // clearInterval(timer);
          // timer = null;
          // }
        } else {
          duration.value = '0';
          status.value = 'exception';
          typeName.value = $t('smt.processingfailure');
          ElMessage.error(res.msg);
          // clearInterval(timer);
          // timer = null;
        }
      }
      // }, 3000);
    });
  }
};

const statisticalData = reactive({
  totalBomAmount: 0,
  singleBomAmount: 0,
  expiredTime: 0,
  similarity: {},
  modelConfirmed: 0,
  modelDetermined: 0,
  allType: 0,
  createTime: '',
  updateTime: '',
  confirmExactmatch: 0,
});

/**
 * 获取统计数据
 */
const getStatisticalData = () => {
  const obj = {
    bomFileId: bomFileId.value,
  };
  getBomMatchListStatisticsData(obj).then((res) => {
    if (res.code == 200) {
      console.log(res);

      statisticalData.totalBomAmount = res.data.totalBomAmount;
      statisticalData.singleBomAmount = res.data.singleBomAmount;
      statisticalData.expiredTime = res.data.expiredTime;
      statisticalData.similarity = res.data.similarity;
      statisticalData.modelConfirmed =
        Number(statisticalData.similarity['2']) +
        Number(statisticalData.similarity['3']) +
        Number(statisticalData.similarity['4']) +
        Number(statisticalData.similarity['5']);
      statisticalData.confirmExactmatch =
        Number(statisticalData.similarity['3']) +
        Number(statisticalData.similarity['4']) +
        Number(statisticalData.similarity['5']);
      statisticalData.modelDetermined =
        Number(statisticalData.similarity['1']) + Number(statisticalData.similarity['6']);
      statisticalData.allType =
        Number(statisticalData.similarity['1']) +
        Number(statisticalData.similarity['2']) +
        Number(statisticalData.similarity['3']) +
        Number(statisticalData.similarity['4']) +
        Number(statisticalData.similarity['5']) +
        Number(statisticalData.similarity['6']);
    } else {
      ElMessage.error(res.msg);
    }
  });
};

/**
 * 确认 BOM 配单
 */
const handleClick = () => {
  const obj = {
    bomFileId: bomFileId.value,
  };
  const params = {
    bomFileId: bomFileId.value,
    current: 1,
    pageSize: 10,
    patchStatus: 1,
    similarity: '',
    status: '',
  };
  Promise.all([getQueryPageList(params), getBomMatchListStatisticsData(obj)])
    .then((res) => {
      if (res[0].code == 200 && res[1].code == 200) {
        emit('getCacheData');
        bomData.value = res;
        router.push({
          path: '/quotation',
          query: {
            bomName: flieData.bomName,
            fileSerial: flieData.fileSerial,
            bomFileId: bomFileId.value,
            patchNum: props.patchNum, // bom 匹配数量
            beforeOrderType: 'bom',
          },
        });
      }
    })
    .catch((error) => {
      // 处理请求错误
      ElMessage.error(error);
    });
};

watchEffect(() => {
  if (props.fileUploadRequest) {
    parsingProgress();
  }
});

// onMounted(() => {
// });

// 下载BOM
const downloadBom = () => {
  if (!props.fileUploadRequest.path) {
    return ElMessage.error('暂无文件可供下载');
  }
  const { path: filePath, name: fileName } = props.fileUploadRequest;
  downloadFile(filePath, fileName);
};

onUnmounted(() => {
  clearInterval(timer);
  timer = null;
});
</script>
<style scoped lang="scss">
.suess {
  color: #52c41a;
}
.price {
  color: #ff8d1a;
}
.co {
  color: var(--mall-color-primary);
  cursor: pointer;
}
.icon-co {
  color: red;
}
.progress-box {
  padding: 10px;
  display: grid;
  justify-content: center;
  width: 100%;
  height: 100%;
  position: relative;
  margin-bottom: 24px;
  .h3 {
    margin-top: 20px;
    text-align: center;
  }
  .progress-box-header {
    display: flex;
    margin-top: 20px;
    span {
      color: #383838;
      font-size: 16px;
    }
    .title {
      padding-right: 40px;
      width: 70px;
      display: inline-block;
    }
  }
  .progress-box-footer {
    width: 100%;
    height: 36px;
    div {
      height: 100%;
      display: flex;
      justify-content: end;
    }
  }
  .flex {
    display: flex;
    // align-items: center;
    justify-content: space-between;
  }
  .info-data {
    width: 100%;
    height: 50px;
    line-height: 50px;
    color: #383838;
    font-size: 16px;
    font-weight: 500;
    border-bottom: 1px solid #d4d4d4;
  }
  .b-t {
    border-top: 1px solid #d4d4d4;
  }
  .info-datas {
    width: 100%;
    height: 50px;
    line-height: 50px;
    color: #383838;
    font-size: 16px;
    font-weight: 500;
  }

  .info-type {
    width: 100%;
    height: 40px;
    line-height: 40px;
    color: #383838;
    font-size: 16px;
    font-weight: 500;
  }
  .f-14 {
    font-size: 14px;
  }
}
.progress-box .el-progress--line {
  width: 700px;
  // margin-bottom: 50px;
}
</style>
